<template>
	<leaderMessage :statusList="statusList" @statusChange="statusChange" @completeOrder="completeOrder" @getExcel="getExcel"></leaderMessage>
	
	<view class="mask" v-if="dialogVisible">
		<view class="dialog">
			<view class="hd">
				<view class="title">
					请输入截排的谷子套数
				</view>
				<view class="back" @click='dialogVisible=false'>
					返回
				</view>
			</view>
			<view class="bd">
				<input type="number" style="height: 100%;" v-model="expectQuantity">
			</view>
			<view class="btn" @click="ConfirmchangeStatus">
				确定
			</view>
			
		</view>
	</view>
</template>

<script>
	import {getCreatorTruncationResult,truncationOnClick,completeOrderOnClick,exportExcel} from '@/api/goods.js'
	import leaderMessage from '../../../src/components/leaderMessage/leaderMessage.vue'
	export default {
		components:{
			leaderMessage
		},
		onShow() {
			this.getResult()
		},
		data() {
			return {
				goodsStatus:{},
				statusList:[],
				goodsId:null,
				expectQuantity:null,
				dialogVisible:false
			};
		},
		methods:{
			getResult(){
				getCreatorTruncationResult().then(res=>{
					if(res.data.code==200){
						this.goodsStatus=res.data.data
						this.getAllStatus()
						console.log(this.statusList)
					}
				})
			},
			getAllStatus(){
				let that=this
				that.statusList=[]
				Object.keys(this.goodsStatus).forEach(key=>{
					if (that.goodsStatus[key] instanceof Array) {
					    that.statusList.push(...that.goodsStatus[key])
					}
				})
				console.log(this.goodsStatus)
			},
			statusChange(goodsId){
				this.goodsId=goodsId
				this.dialogVisible=true
			},
			ConfirmchangeStatus(){
				let data={
					goodsId:this.goodsId,
					quantity:this.expectQuantity
				}
				truncationOnClick(data).then(res=>{
					if(res.data.code==200){
						uni.showToast({
							title:'截排成功',
							icon:'none'
						})
						this.dialogVisible=false
						this.getResult()
					}else{
						uni.showToast({
							title:`${res.data.message}`,
							icon:'none'
						})
					}
				})
			},
			completeOrder(goodsId){
				completeOrderOnClick(goodsId).then(res=>{
					if(res.data.code==200){
						uni.showToast({
							title:'订单完成',
							icon:'none'
						})
						this.getResult()
					}else{
						uni.showToast({
							title:`${res.data.message}`,
							icon:'none'
						})
					}
				})
			},
			getExcel(goodsId){
			  let userInfo = uni.getStorageSync('userInfo');
			  let token = userInfo.token || null
				uni.downloadFile({
				  url: `http://127.0.0.1:9090/gbg/goodsTruncation/exportExcel?goodsId=${goodsId}`,
				  method: 'GET',
				  header: {
				    'Authorization': token
				  },
				  success: function (res) {
				    if (res.statusCode === 200) {
				      // 下载成功，手动指定文件保存的路径
				      const tempFilePath = res.tempFilePath;
					  const encodedFileName = decodeURIComponent(res.header['Content-Disposition'].match(/filename="(.*)"/)[1]);
					  const cleanFileName = encodedFileName.replace(/"/g, '');
				      // 使用 uni.getFileSystemManager() 来保存文件到用户数据目录
				      const fs = uni.getFileSystemManager();
				      const userDirectory = `${uni.env.USER_DATA_PATH}/your_folder/`;
				      // 确保目录存在，如果不存在则创建目录
					  fs.access({
						  path:userDirectory,
						  success:function(){
							  saveFile()
						  },
						  fail:function(){
							  fs.mkdir({
							    dirPath: userDirectory,
							    recursive: true,
							    success: function () {
							       saveFile()
							    },
							    fail: function (mkdirErr) {
							      console.error('创建目录失败', mkdirErr);
							    }
							  });
						  }
					  })
				      
					  function saveFile(){
						  const fileName = cleanFileName.split('/').pop();
						  // 修改文件后缀名为 ".xls"
						  const newFileName = fileName.replace(/\.xlsx$/, '.xls');
						  fs.saveFile({
						    tempFilePath,
						    filePath: userDirectory + newFileName, // 使用 fileName 作为文件名
						    success: function (saveRes) {
						      // 现在文件将保存在指定的路径下，文件名为 fileName
						      const savedFilePath = saveRes.savedFilePath;
						      console.log('保存的文件路径:', savedFilePath);
						      // 如果需要打开文件，可以使用 uni.openDocument 方法
						      uni.openDocument({
						        filePath: savedFilePath,
						        success: function (openRes) {
						          console.log('文件打开成功', openRes);
						        },
						        fail: function (openErr) {
						          console.error('文件打开失败', openErr);
						        }
						      });
						    },
						    fail: function (saveErr) {
						      console.error('保存文件失败', saveErr);
						    }
						  });
					  }
				    } else {
				      console.error('下载失败', res);
				    }
				  },
				  fail: function (err) {
				    console.error('下载失败', err);
				  }
				});
			},
		}
	}
</script>

<style lang="scss">
.mask{
		position: fixed;
		  top: 0;
		  left: 0;
		  width: 100%;
		  height: 100%;
		  background-color: rgba(0, 0, 0, 0.5);
		  z-index: 9999;
		  .dialog{
			  position: fixed;
			  top: 35%;
			  left: 15%;
			  display: flex;
			  flex-direction: column;
			  justify-content: space-around;
			  padding: 30rpx;
			  background-color: #fff;
			  width: 500rpx;
			  height: 300rpx;
			  font-size: 32rpx;
			  .hd{
				  display: flex;
				  justify-content: space-between;
				  .back{
					  color: #347CD4;
				  }
			  }
			  .bd{
				  height: 80rpx;
				  background-color: #f8f8f8;
			  }
			 .btn{
				 color: #347CD4;
				 background-color: #E3F1F7;
				 height: 70rpx;
				 line-height: 70rpx;
				 border-radius: 35rpx;
				 text-align: center;
			 }
		  }
}
</style>
